<template>
  <div>
    <!-- 上传按钮 -->
    <el-upload
      class="avatar-uploader"
      action="/api/oss/uploadFile"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <!-- 文件预览 -->
    <el-dialog :visible.sync="dialogVisible" width="30%">
      <img style="max-width: 100%" :src="imageUrl" alt="预览" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["isAdd"],
  data() {
    return {
      imageUrl: "", // 预览图地址
      dialogVisible: false, // 是否显示预览弹窗
      //   dialogTop: "150px", // 设置弹窗的上边距
      //   dialogLeft: "1000px", // 设置弹窗的左边距
      responseFileName: "", //上传后返回的文件名
    };
  },
  computed: {
    action() {
      return this.$store.state.ipAddr + "/";
    },
  },
  methods: {
    // 上传前的钩子函数
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件");
        return false;
      }
      // 清空之前的预览图
      this.imageUrl = "";
    },
    // 上传成功的钩子函数
    handleSuccess(response, file) {
      //读取添加的本地文件
      this.imageUrl = URL.createObjectURL(file.raw);

      console.log(response.fileName);
      console.log(response);

      //注册的时候可取到上传的文件名
      this.responseFileName = response.fileName

      //判断是新增还是更新
      if (!this.isAdd) {
        //不是新增，更新用户头像
        this.updateAvatarByUserId(response);
      }

      //   this.dialogVisible = true; // 显示，可在需要时调用预览弹窗
    },
    updateAvatarByUserId(response) {
      //更新用户头像
      this.$request.postHttp({
        url: "/user/updateAvatarByUserId",
        data: {
          userid: localStorage.getItem("userId"),
          avatar: response.fileName,
        },
        success: (data) => {
          console.log("data", data);
          if (data.isUpdate) {
            this.$message({
              message: "上传成功",
              type: "success",
            });
          }
        },
        error: (error) => {
          this.$message({
            message: "上传失败",
            type: "error",
          });
        },
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  position: relative;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

/* .el-dialog__wrapper {
  width: 60%;
} */
</style>
